<template>
	<view class="container order">
		<!-- 收货地址区域 -->
		<view class="address-card">
			<!-- 添加收货地址 -->
			<view v-if="!orderAddress.id">
				<navigator class="add-address" url="/modules/settingModule/pages/address/add/add">
					<uni-icons type="plus-filled" size="20"></uni-icons>
					<view>添加收货地址</view>
				</navigator>
			</view>

			<!-- 渲染收货地址 -->
			<view v-else class="order-address detail-flex">
				<view class="address-content">
					<view class="title">{{orderAddress.fullAddress}}</view>
					<view class="info detail-flex">
						<text>{{orderAddress.name}}</text>
						<text>{{orderAddress.phone}}</text>
					</view>
				</view>

				<view class="select-address">
					<!-- 添加 flag 标识，是为了区分是否是从结算支付页面进入的收货地址列表页面 -->
					<!-- 如果是，在点击收货地址时，就需要给全局共享的 address 进行赋值 -->
					<navigator class="navigator" url="/modules/settingModule/pages/address/list/list?flag=1">
						<uni-icons class="icons" color='#bbb' type="right" size="23"></uni-icons>
					</navigator>
				</view>
			</view>
		</view>

		<!-- 订单信息区域 -->
		<view class="order-info">
			<view class="group">
				<uni-forms ref='form' :rules="rules" :modelValue="formData">
					<uni-forms-item class="name" label="姓名" name="name">
						<uni-easyinput :clearable='false' type="text" v-model="formData.name" placeholder="请输入姓名" />
					</uni-forms-item>
					<uni-forms-item class="phone" label="手机号" name="phone">
						<uni-easyinput :clearable='false' type="number" v-model="formData.phone" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item class="data" label="送达日期(三个月内)" name="date">
						<view class="example-body">
							<uni-datetime-picker type="date" v-model="formData.date" :start="Date.now()"
								:end="Date.now() + (3 * 30 * 24 * 60 * 60 * 1000)" />
						</view>
					</uni-forms-item>
					<uni-forms-item class="remarks" label="订单备注" name="remarks">
						<uni-easyinput :maxlength='-1' :clearable='false' type="textarea" autoHeight
							v-model="formData.remarks" placeholder="备注内容" />
					</uni-forms-item>
				</uni-forms>
			</view>
		</view>

		<!-- 订单商品信息 -->
		<view class="goods-wraper">
			<!-- 商品清单 -->
			<view class="goods-list">
				<view class="goods-item detail-flex" v-for="(item,index) in  orderInfo.cartVoList" :key="item.goodsId">
					<view class="img">
						<image :src="item.imageUrl" />
					</view>
					<view class="content">
						<view class="goods-title">{{item.name}}</view>
						<view class="goods-price">
							<view class="price"> ¥ {{item.price}} </view>
							<view>x{{item.count}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部支付区域 -->
		<view class="footer detail-flex">
			<view class="left"> ¥{{orderInfo.totalAmount}} </view>
			<view @click="submit" class="right">提交订单</view>
		</view>
	</view>
</template>

<script setup>
	import { toast } from "@/utils/extendApi.js"
	import {
		reqBuyNowGoods,
		reqOrderAdress,
		reqOrderInfo,
		reqSubmitOrder,
		reqPayStatus,
		reqPrePayInfo
	} from '@/api/orderpay.js'
	import { reactive } from "vue";

	let form = ref()
	let formData = reactive({
		name: '', //订购人姓名
		phone: '',
		date: Date.now(),
		remarks: ''
	})
	let orderAddress = reactive({}) //收货地址
	let orderInfo = reactive({}) // 订单商品详情
	let detailToNowBuy = reactive({}) // 商品详情 =>  立即购买
	let orderNo = ref('') // 订单编号


	// 收货人姓名规则
	const valiName = (rule, value, data, callback) => {
		let regexp = /^[\u4e00-\u9fa5]{2,6}$/

		if (regexp.test(value)) {
			callback()
		} else {
			callback('请输入2-6个中文字符')
		}
	}

	// 手机号规则
	const valiPhone = (rule, value, data, callback) => {
		let regexp = /^1[3-9]\d{9}$/

		if (regexp.test(value)) {
			callback()
		} else {
			callback('请输入大陆手机号格式')
		}
	}

	// form规则
	let rules = ref({
		name: {
			rules: [

				{
					required: true,
					validateFunction: valiName,
					errorMessage: '请填写{label}',
				},
			],
			label: '姓名'
		},
		phone: {
			rules: [

				{
					required: true,
					validateFunction: valiPhone,
					errorMessage: '请填写手机号',
				}
			]
		},
		date: { rules: [{ required: true, errorMessage: '请选择日期', }] },
		remarks: { rules: [{ required: true, errorMessage: '请填写备注信息', }] }
	})

	// 提交订单按钮
	const submit = () => {
		// 组织请求参数
		const params = {
			buyName: formData.name,
			buyPhone: formData.phone,
			cartList: orderInfo.cartVoList,
			deliveryDate: formData.date,
			remark: formData.remarks,
			userAddressId: orderAddress.id
		}

		form.value.validate().then(async () => {
			let res = await reqSubmitOrder(params)
			orderNo.value = res.data

			advancePay()
		}).catch(err => {
			toast({ title: '提交失败' })
		})
	}

	// 获取预付单信息
	const advancePay = async () => {
		// 支付参数
		let payParams = await reqPrePayInfo(orderNo.value)

		// 获取平台服务供应商
		let servicePay = await uni.getProvider({
			service: 'payment',
		})

		// 发起支付
		let payInfo = await uni.requestPayment({
			provider: servicePay.provider[0],
			...payParams.data
		}) // 返回失败，因为没有做相应的支付申请流程

		// 获取支付结果
		if (payInfo.errMsg == 'requestPayment:ok') {
			let payStatus = await reqPayStatus(orderNo.value)
			if (payStatus.code == 200) {
				uni.navigateTo({
					url: "/modules/orderPayModule/pages/order/list/list",
					success: () => {
						toast({ title: '支付成功', icon: 'success' })
					}
				})
			}
		}

	}

	// 获取订单页面收货地址
	const getAddress = async () => {
		// 若全局共享 address 中存在数据
		if (getApp().globalData.address.id) {
			Object.assign(orderAddress, getApp().globalData.address)
			return
		}

		// 若全局共享 无address 中存在数据，发请求获取地址
		let result = await reqOrderAdress()
		// 地址列表没有地址
		if (!result.data) {
			Object.assign(orderAddress, { id: null })
			return
		}
		Object.assign(orderAddress, result.data)
	}

	// 订单详情数据
	const getOrderInfo = async () => {
		let { goodsId, blessing } = detailToNowBuy

		// 若有id说明是从：商品详情 => 立即购买 来的
		let result = goodsId ? await reqBuyNowGoods({ goodsId, blessing }) : await reqOrderInfo()

		Object.assign(orderInfo, result.data)

		// 若有多个商品，找到第一个拥有祝福语的商品就是订单备注；没找到返回undefined
		let orderGoods = orderInfo.cartVoList.find(item => item.blessing !== '')
		formData.remarks = orderGoods ? orderGoods.blessing : ''
	}

	onLoad((options) => {
		Object.assign(detailToNowBuy, options)
	})

	onShow(() => {
		getAddress()
		getOrderInfo()
	})

	onReady(() => {
		form.value.setRules(rules.value)
	})
</script>

<style lang="scss" scoped>
	/* pages/order/index.wxss */

	.detail-flex {
		display: flex;
	}

	.order {
		padding: 16rpx;
		background-color: rgba(230, 230, 230, 0.5);
		padding-bottom: 130rpx;
	}

	// 收货地址卡片
	.address-card {
		background-color: #fff;
		border-radius: 14rpx;
		overflow: hidden;

		// 添加收货地址
		.add-address {
			display: flex;
			height: 140rpx;
			line-height: 140rpx;
			justify-content: center;

			view {
				padding-left: 14rpx;
			}
		}

		// 收货地址样式
		.order-address {
			justify-content: space-between;
			padding: 24rpx 32rpx;

			.title {
				display: flex;
				align-items: center;
				// height: 60rpx;
				font-size: 28rpx;
				font-weight: normal;
				color: #333333;
				line-height: 40rpx;
			}

			.info {
				height: 60rpx;
				font-size: 28rpx;
				font-weight: normal;
				color: #333333;
				line-height: 40rpx;
				margin-top: 20rpx;

				text {
					&:first-child {
						margin-right: 16rpx;
					}
				}
			}

			.select-address .navigator {
				width: 100%;
				height: 100%;
				width: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.icons {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}
	}

	.order-info {
		background-color: white;
		padding: 24rpx 24rpx;
		margin-top: 20rpx;
		border-radius: 14rpx;

		.group {
			padding: 16rpx;

			.name {}
		}
	}

	// 提交订单面板
	.footer {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		background-color: #fff;
		height: 112rpx;
		justify-content: space-between;
		align-items: center;
		border-top: 1px solid #ddd;

		.left {
			color: #fa4126;
			font-weight: bold;
			font-size: 50rpx;
			line-height: 88rpx;
			margin-left: 16px;
		}

		.right {
			height: 80rpx;
			width: 240rpx;
			border-radius: 40rpx;
			background-color: #fa4126;
			color: #ffffff;
			line-height: 80rpx;
			font-weight: bold;
			font-size: 28rpx;
			text-align: center;
			margin-right: 16px;
		}
	}

	// 外部样式类
	.filed-label {
		color: #333333 !important;
		width: 400rpx !important;
	}

	.input-class {
		color: #333333 !important;
	}

	.order-info,
	.goods-wraper {
		background-color: white;
		padding: 24rpx 0rpx;
		margin-top: 20rpx;
		border-radius: 14rpx;
	}

	.goods-wraper {
		padding: 10rpx 24rpx;

		.goods-list {
			padding: 12px 0;

			.goods-item {
				display: flex;
				margin-bottom: 14px;

				.img {
					width: 64px;
					height: 69px;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.content {
					flex: 1;
					margin: 0 8px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.goods-title {
						font-size: 14px;
						color: #333;
					}
				}

				.goods-price {
					display: flex;
					justify-content: space-between;
					font-size: 30rpx;
				}
			}
		}
	}
</style>